'use strict';

const fs = require('fs');
const path = require('path');
const router = require('koa-router')();

function getRouter(reqPath) {
    reqPath = reqPath || __dirname;
    reqPath = path.resolve(reqPath);
    return fs.readdirSync(reqPath).filter(item => item !== 'index.js').map(item => path.join(reqPath, item));
}

function regRouter(router, reqPath) {
    let routerFL = getRouter(reqPath);
    for (const routeFile of routerFL) {
        const routes = require(routeFile);
        for (const key in routes) {
            const route = routes[key];
            if (typeof route === 'function') {
                const [reqMethod, reqPath] = key.split(' ');
                (reqMethod);
                if (reqMethod === 'get') {
                    router.get(reqPath, route)
                } else if (reqMethod === 'post') {
                    router.post(reqPath, route);
                } else if (reqMethod === 'put') {
                    router.put(reqPath, route);
                } else if (reqMethod === 'delete') {
                    router.del(reqPath, route);
                } else {
                    console.error(`Error request method:\n${key}`);
                }
            } else {
                console.error(`Invalid Route:\n${route}.`);
            }
        }
    }
    return router.routes();
}

module.exports = () => regRouter(router);
